﻿using HDSmartCommunity.BUS;
using HDSmartCommunity.DAL;
using HDSmartCommunity.DevicePlatform;
using HDSmartCommunity.Models;
using HDSmartCommunity.Serial;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace HDSmartCommunity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AudioController : ControllerBase
    {
        public SHGDLine18SerialData sHGDLine = SerialServer.sHGDLine18SerialData;
        [Obsolete]
        private readonly IHostingEnvironment _hostingEnvironment;
        [Obsolete]
        public AudioController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 新增音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("InsertAudio")]
        public ResponseMessage InsertAudio(AudioInfo audioInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                AudioDAL audioDAL = new AudioDAL();
                string[] array = audioInfo.filename.Split('.');
                if (audioInfo.id.ToString().PadLeft(4, '0') != array[0])
                {
                    message.errcode = 1;
                    message.errmsg = "文件名编号与所选编号不一致";
                }
                else
                {
                    bool result = audioDAL.InsertAudio(audioInfo);
                    if (result)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "新增失败";
                    }
                }

            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 下发音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("IssueAudio")]
        [Obsolete]
        public ResponseMessage IssueAudio(AudioInfo audioInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (SHGDLine18SerialData.upload_flag)
                {
                    message.errcode = 1;
                    message.errmsg = "有音频文件在上传，请稍后";
                    return message;
                }
                SHGDLine18SerialData.yy_cmd_list.Clear();
                //起始帧
                string webRootPath = _hostingEnvironment.ContentRootPath;
                string filePath = webRootPath + "/wwwroot" + audioInfo.path;
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                //文件名
                byte[] filename_buffer = stringToHexByte(audioInfo.filename);
                //文件大小
                byte[] filelength = stringToHexByte(fs.Length.ToString());

                byte[] myByteArray = Enumerable.Repeat((byte)0x00, 128).ToArray();

                Array.Copy(filename_buffer, 0, myByteArray, 0, filename_buffer.Length);
                Array.Copy(filelength, 0, myByteArray, filename_buffer.Length + 1, filelength.Length);
                byte[] crc_data = CrcXmodem(myByteArray);
                byte[] StartFrame = new byte[133];
                StartFrame[0] = 0x01;
                StartFrame[1] = 0x00;
                StartFrame[2] = 0xFF;
                Array.Copy(myByteArray, 0, StartFrame, 3, myByteArray.Length);
                StartFrame[131] = crc_data[0];
                StartFrame[132] = crc_data[1];
                LogHelper.Log(ToHexs(StartFrame));
                YYData yYFData = new YYData();
                yYFData.type = "start";
                yYFData.data = StartFrame;
                SHGDLine18SerialData.yy_cmd_list.Add(yYFData);

                double fs_length = fs.Length;
                int ceilingValue = Convert.ToInt32(Math.Ceiling(fs_length / 1024));
                for (int i = 0; i < ceilingValue; i++)
                {
                    if (ceilingValue - 1 == i)
                    {
                        if ((i + 1) * 1024 == fs.Length)
                        {
                            byte[] bytes = new byte[1024];
                            Array.Copy(buffer, i * 1024, bytes, 0, 1024);
                            byte[] crc = CrcXmodem(bytes);
                            byte[] DataFrame = new byte[1029];
                            DataFrame[0] = 0x02;
                            DataFrame[1] = (byte)(i + 1);
                            DataFrame[2] = (byte)(254 - i);
                            Array.Copy(bytes, 0, DataFrame, 3, 1024);
                            DataFrame[1027] = crc[0];
                            DataFrame[1028] = crc[1];
                            YYData yData = new YYData();
                            yData.type = "data";
                            yData.data = DataFrame;
                            SHGDLine18SerialData.yy_cmd_list.Add(yData);
                        }
                        else
                        {
                            int data_length = Convert.ToInt32(fs.Length - i * 1024);
                            if (data_length > 128)
                            {
                                byte[] bytes = Enumerable.Repeat((byte)0x00, 1024).ToArray();
                                Array.Copy(buffer, i * 1024, bytes, 0, data_length);
                                byte[] crc = CrcXmodem(bytes);
                                byte[] DataFrame = new byte[1029];
                                DataFrame[0] = 0x02;
                                DataFrame[1] = (byte)(i + 1);
                                DataFrame[2] = (byte)(254 - i);
                                Array.Copy(bytes, 0, DataFrame, 3, 1024);
                                DataFrame[1027] = crc[0];
                                DataFrame[1028] = crc[1];
                                YYData yData = new YYData();
                                yData.type = "data";
                                yData.data = DataFrame;
                                SHGDLine18SerialData.yy_cmd_list.Add(yData);
                            }
                            else
                            {
                                byte[] bytes = Enumerable.Repeat((byte)0x00, 128).ToArray();
                                Array.Copy(buffer, i * 1024, bytes, 0, data_length);
                                byte[] crc = CrcXmodem(bytes);
                                byte[] DataFrame = new byte[133];
                                DataFrame[0] = 0x01;
                                DataFrame[1] = (byte)(i + 1);
                                DataFrame[2] = (byte)(254 - i);
                                Array.Copy(bytes, 0, DataFrame, 3, 128);
                                DataFrame[131] = crc[0];
                                DataFrame[132] = crc[1];
                                YYData yData = new YYData();
                                yData.type = "data";
                                yData.data = DataFrame;
                                SHGDLine18SerialData.yy_cmd_list.Add(yData);
                            }
                        }
                    }
                    else
                    {
                        byte[] bytes = new byte[1024];
                        Array.Copy(buffer, i * 1024, bytes, 0, 1024);
                        byte[] crc = CrcXmodem(bytes);
                        byte[] DataFrame = new byte[1029];
                        DataFrame[0] = 0x02;
                        DataFrame[1] = (byte)(i + 1);
                        DataFrame[2] = (byte)(254 - i);
                        Array.Copy(bytes, 0, DataFrame, 3, 1024);
                        DataFrame[1027] = crc[0];
                        DataFrame[1028] = crc[1];
                        YYData yData = new YYData();
                        yData.type = "data";
                        yData.data = DataFrame;
                        SHGDLine18SerialData.yy_cmd_list.Add(yData);
                    }
                }

                SHGDLine18SerialData.SwitchingProtocol(1);
                SHGDLine18SerialData.upload_flag = true;
                SHGDLine18SerialData.yy_id = audioInfo.id;
                while (SHGDLine18SerialData.upload_flag)
                {

                }
                if (SHGDLine18SerialData.success)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;

                }
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 播放音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("PlayAudio")]
        [Obsolete]
        public ResponseMessage PlayAudio(AudioInfo audioInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                SHGDLine18SerialData.SwitchingProtocol(2);
                Wait(100);
                byte[] bytes = new byte[9] { 0x01, 0x10, 0x00, 0x15, 0x00, 0x01, 0x02, 0x00, 0x00 };
                byte[] volume_data = BitConverter.GetBytes(audioInfo.id);
                bytes[7] = volume_data[1];
                bytes[8] = volume_data[0];
                byte[] crc = Crc18(bytes);
                byte[] data_crc = new byte[2];
                data_crc[0] = crc[1];
                data_crc[1] = crc[0];
                string cmd = ToHexs(bytes) + ToHexs(data_crc);
                SHGDLine18SerialData.ttyS1SendMsg(cmd);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 取消上传
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("CancelUpload")]
        [Obsolete]
        public ResponseMessage CancelUpload()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                SHGDLine18SerialData.yy_cmd_list.Clear();
                SHGDLine18SerialData.upload_flag = false;
                SHGDLine18SerialData.start_flag = false;
                SHGDLine18SerialData.data_flag = false;
                SHGDLine18SerialData.data_ack_flag = false;
                SHGDLine18SerialData.eot_flag = false;
                SHGDLine18SerialData.end_ack_flag = false;
                SHGDLine18SerialData.end_flag = false;
                SHGDLine18SerialData.success = false;
                SHGDLine18SerialData.fail_count = 0;
                SHGDLine18SerialData.yy_id = 0;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        public bool Wait(int second)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                while (true)
                {
                    TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                    if (secondSpan.TotalMilliseconds > second)
                    {
                        break;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 音量设置
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("VolumeSet")]
        [Obsolete]
        public ResponseMessage VolumeSet(int volume)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                SHGDLine18SerialData.SwitchingProtocol(2);
                Wait(100);
                byte[] bytes = new byte[9] { 0x01, 0x10, 0x00, 0x14, 0x00, 0x01, 0x02, 0x00, 0x00 };
                byte[] volume_data = BitConverter.GetBytes(volume);
                bytes[7] = volume_data[1];
                bytes[8] = volume_data[0];
                byte[] crc = Crc18(bytes);
                byte[] data_crc = new byte[2];
                data_crc[0] = crc[1];
                data_crc[1] = crc[0];
                string cmd = ToHexs(bytes) + ToHexs(data_crc);
                SHGDLine18SerialData.ttyS1SendMsg(cmd);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 修改音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateAudioFile")]
        public ResponseMessage QueryAudioFile(AudioInfo audioInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                AudioDAL audioDAL = new AudioDAL();
                bool result = audioDAL.UpdateAudio(audioInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "新增失败";
                }
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 删除音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("DeleteAudioFile")]
        public ResponseMessage DeleteAudioFile(AudioInfo audioInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                AudioDAL audioDAL = new AudioDAL();
                bool result = audioDAL.DeleteAudio(audioInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "新增失败";
                }
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 查询音频文件
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryAudioFile")]
        public ResponseMessage QueryAudioFile()
        {
            ResponseMessage message = new ResponseMessage();
            List<AudioInfo> list = new List<AudioInfo>();
            try
            {
                AudioDAL audioDAL = new AudioDAL();
                list = audioDAL.QueryAudio();
                message.data = list;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 上行控制
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("ControlAscending")]
        public ResponseMessage ControlAscending()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                Line18Cmd line18Cmd = new Line18Cmd();
                byte[] data_bytes = new byte[9];
                byte[] bytes = new byte[11];
                byte[] ykz_bytes = new byte[11];
                data_bytes[0] = (byte)(sHGDLine.liftid & 0xff);
                data_bytes[1] = 0x10;
                data_bytes[2] = 0x00;
                data_bytes[3] = 0x05;
                data_bytes[4] = 0x00;
                data_bytes[5] = 0x01;
                data_bytes[6] = 0x02;
                data_bytes[7] = 0x04;
                data_bytes[8] = 0x00;
                byte[] crc = Crc18(data_bytes);
                Array.Copy(data_bytes, 0, bytes, 0, 9);
                bytes[9] = crc[1];
                bytes[10] = crc[0];

                data_bytes[7] = 0x20;
                byte[] crc_2 = Crc18(data_bytes);
                Array.Copy(data_bytes, 0, ykz_bytes, 0, 9);
                ykz_bytes[9] = crc_2[1];
                ykz_bytes[10] = crc_2[0];
                line18Cmd.cmd = ToHexs(bytes);
                line18Cmd.type = 1;
                line18Cmd.activateCmd = ToHexs(ykz_bytes);
                sHGDLine.cmds.Add(line18Cmd);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 下行控制
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("ControlDescending")]
        public ResponseMessage ControlDescending()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                Line18Cmd line18Cmd = new Line18Cmd();
                byte[] data_bytes = new byte[9];
                byte[] bytes = new byte[11];
                byte[] ykz_bytes = new byte[11];
                data_bytes[0] = (byte)(sHGDLine.liftid & 0xff);
                data_bytes[1] = 0x10;
                data_bytes[2] = 0x00;
                data_bytes[3] = 0x05;
                data_bytes[4] = 0x00;
                data_bytes[5] = 0x01;
                data_bytes[6] = 0x02;
                data_bytes[7] = 0x08;
                data_bytes[8] = 0x00;
                byte[] crc = Crc18(data_bytes);
                Array.Copy(data_bytes, 0, bytes, 0, 9);
                bytes[9] = crc[1];
                bytes[10] = crc[0];

                data_bytes[7] = 0x20;
                byte[] crc_2 = Crc18(data_bytes);
                Array.Copy(data_bytes, 0, ykz_bytes, 0, 9);
                ykz_bytes[9] = crc_2[1];
                ykz_bytes[10] = crc_2[0];
                line18Cmd.cmd = ToHexs(bytes);
                line18Cmd.type = 1;
                line18Cmd.activateCmd = ToHexs(ykz_bytes);

                sHGDLine.cmds.Add(line18Cmd);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 停梯控制
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("ControlStop")]
        public ResponseMessage ControlStop()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                Line18Cmd line18Cmd = new Line18Cmd();
                byte[] data_bytes = new byte[9];
                byte[] bytes = new byte[11];
                data_bytes[0] = (byte)(sHGDLine.liftid & 0xff);
                data_bytes[1] = 0x10;
                data_bytes[2] = 0x00;
                data_bytes[3] = 0x05;
                data_bytes[4] = 0x00;
                data_bytes[5] = 0x01;
                data_bytes[6] = 0x02;
                data_bytes[7] = 0x10;
                data_bytes[8] = 0x00;
                byte[] crc = Crc18(data_bytes);
                Array.Copy(data_bytes, 0, bytes, 0, 9);
                bytes[9] = crc[1];
                bytes[10] = crc[0];

                line18Cmd.cmd = ToHexs(bytes);
                line18Cmd.type = 0;
                line18Cmd.activateCmd = "";

                sHGDLine.cmds.Add(line18Cmd);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 查询实时状态
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryState")]
        public ResponseMessage QueryState()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (sHGDLine.Simulation == 1)
                {
                    message.data = sHGDLine.Line18State;
                }
                else
                {
                    Line18State line18State = new Line18State();
                    if (sHGDLine.fTLine18ParamInfo.ZDFT_YX_ZT == null)
                    {
                        line18State.fx = 4;
                        line18State.yx = false;
                        line18State.jx = false;
                        line18State.gz = false;
                        line18State.jt = false;
                        line18State.yms = false;
                        line18State.jnyx = false;
                        line18State.dsyx = false;
                        line18State.gsyx = false;
                        line18State.qsyx = false;
                        line18State.bp = false;
                        line18State.zdyx = false;
                        line18State.sxyx = false;
                        line18State.lxyx = false;
                        line18State.gzdm = "";
                        line18State.xt = false;
                        message.data = line18State;
                    }
                    else
                    {
                        FTLine18ParamInfo fTLine18ParamInfo = sHGDLine.fTLine18ParamInfo;
                        line18State.fx = fTLine18ParamInfo.ZDFT_SX_ZT.value ? 0 : fTLine18ParamInfo.ZDFT_XX_ZT.value ? 1 : fTLine18ParamInfo.ZDFT_TZ_ZT.value ? 2 : 3;
                        line18State.yx = fTLine18ParamInfo.ZDFT_YX_ZT.value;
                        line18State.jx = fTLine18ParamInfo.ZDFT_JX_BJ.value;
                        line18State.gz = fTLine18ParamInfo.ZDFT_GZ_BJ.value;
                        line18State.jt = fTLine18ParamInfo.ZDFT_JT_BJ.value;
                        line18State.yms = fTLine18ParamInfo.ZDFT_Y_MS.value;
                        line18State.jnyx = fTLine18ParamInfo.ZDFT_JNYX_MS.value;
                        line18State.dsyx = fTLine18ParamInfo.ZDFT_DSYX_MS.value;
                        line18State.gsyx = fTLine18ParamInfo.ZDFT_GSYX_MS.value;
                        line18State.qsyx = fTLine18ParamInfo.ZDFT_QSYX_MS.value;
                        line18State.bp = fTLine18ParamInfo.ZDFT_BP_MS.value;
                        line18State.zdyx = fTLine18ParamInfo.ZDFT_ZDYX_MS.value;
                        line18State.sxyx = fTLine18ParamInfo.ZDFT_SXYX_MS.value;
                        line18State.lxyx = fTLine18ParamInfo.ZDFT_LXYX_MS.value;
                        line18State.gzdm = fTLine18ParamInfo.ZDFT_GZ_DM.value;
                        line18State.xt = fTLine18ParamInfo.ZDFT_TX_BJ.value;
                        line18State.bzbzdq_wd_left1 = fTLine18ParamInfo.BZBZDQ_WD_LEFT_1.value;
                        line18State.bzbzdq_wd_left2 = fTLine18ParamInfo.BZBZDQ_WD_LEFT_2.value;
                        line18State.bzbzdq_wd_right1 = fTLine18ParamInfo.BZBZDQ_WD_RIGHT_1.value;
                        line18State.bzbzdq_wd_right2 = fTLine18ParamInfo.BZBZDQ_WD_RIGHT_2.value;
                        line18State.totalRunningCounts = fTLine18ParamInfo.TotalRunningCounts.value;
                        line18State.totalRunningTime = fTLine18ParamInfo.TotalRunningTime.value;
                    }

                    if (sHGDLine.fTLine18ParamInfo.HJ_WD != null)
                    {
                        FTLine18ParamInfo fTLine18ParamInfo = sHGDLine.fTLine18ParamInfo;
                        line18State.hj_wd = fTLine18ParamInfo.HJ_WD.value;
                        line18State.kzg_wd = fTLine18ParamInfo.KZG_WD.value;
                        line18State.bpq_wd = fTLine18ParamInfo.BPQ_WD.value;
                        line18State.sbfzl = fTLine18ParamInfo.SBFZL.value;
                        line18State.ztjl = fTLine18ParamInfo.ZTJL.value;
                        line18State.fsdsdpcl = fTLine18ParamInfo.FSDSDPCL.value;
                        line18State.jsdcgq1_qx_rms = fTLine18ParamInfo.JSDCGQ1_QX_RMS.value;
                        line18State.jsdcgq1_hx_rms = fTLine18ParamInfo.JSDCGQ1_HX_RMS.value;
                        line18State.jsdcgq1_cz_rms = fTLine18ParamInfo.JSDCGQ1_CZ_RMS.value;
                        line18State.jsdcgq1_qx_peak = fTLine18ParamInfo.JSDCGQ1_QX_PEAK.value;
                        line18State.jsdcgq1_hx_peak = fTLine18ParamInfo.JSDCGQ1_HX_PEAK.value;
                        line18State.jsdcgq1_cz_peak = fTLine18ParamInfo.JSDCGQ1_CZ_PEAK.value;
                        line18State.jsdcgq2_qx_rms = fTLine18ParamInfo.JSDCGQ2_QX_RMS.value;
                        line18State.jsdcgq2_hx_rms = fTLine18ParamInfo.JSDCGQ2_HX_RMS.value;
                        line18State.jsdcgq2_cz_rms = fTLine18ParamInfo.JSDCGQ2_CZ_RMS.value;
                        line18State.jsdcgq2_qx_peak = fTLine18ParamInfo.JSDCGQ2_QX_PEAK.value;
                        line18State.jsdcgq2_hx_peak = fTLine18ParamInfo.JSDCGQ2_HX_PEAK.value;
                        line18State.jsdcgq2_cz_peak = fTLine18ParamInfo.JSDCGQ2_CZ_PEAK.value;
                        line18State.jsdcgq3_qx_rms = fTLine18ParamInfo.JSDCGQ3_QX_RMS.value;
                        line18State.jsdcgq3_hx_rms = fTLine18ParamInfo.JSDCGQ3_HX_RMS.value;
                        line18State.jsdcgq3_cz_rms = fTLine18ParamInfo.JSDCGQ3_CZ_RMS.value;
                        line18State.jsdcgq3_qx_peak = fTLine18ParamInfo.JSDCGQ3_QX_PEAK.value;
                        line18State.jsdcgq3_hx_peak = fTLine18ParamInfo.JSDCGQ3_HX_PEAK.value;
                        line18State.jsdcgq3_cz_peak = fTLine18ParamInfo.JSDCGQ3_CZ_PEAK.value;
                        line18State.jsdcgq4_qx_rms = fTLine18ParamInfo.JSDCGQ4_QX_RMS.value;
                        line18State.jsdcgq4_hx_rms = fTLine18ParamInfo.JSDCGQ4_HX_RMS.value;
                        line18State.jsdcgq4_cz_rms = fTLine18ParamInfo.JSDCGQ4_CZ_RMS.value;
                        line18State.jsdcgq4_qx_peak = fTLine18ParamInfo.JSDCGQ4_QX_PEAK.value;
                        line18State.jsdcgq4_hx_peak = fTLine18ParamInfo.JSDCGQ4_HX_PEAK.value;
                        line18State.jsdcgq4_cz_peak = fTLine18ParamInfo.JSDCGQ4_CZ_PEAK.value;
                        line18State.alarmCode = fTLine18ParamInfo.AlarmCode.value;
                        line18State.alarmState = fTLine18ParamInfo.AlarmState.value;
                        if (string.IsNullOrEmpty(fTLine18ParamInfo.ZDFT_GZ_DM.value))
                        {
                            line18State.faultCode = 0;
                        }
                        else
                        {
                            line18State.faultCode = Convert.ToInt32(fTLine18ParamInfo.ZDFT_GZ_DM.value);
                        }
                        line18State.faultState = fTLine18ParamInfo.ZDFT_GZ_BJ.value;
                      
                        line18State.baseVibrationSpeed = fTLine18ParamInfo.baseVibrationSpeed.value;
                        line18State.gearboxVibrationSpeed = fTLine18ParamInfo.gearboxVibrationSpeed.value;
                        line18State.mainVibrationSpeed = fTLine18ParamInfo.mainVibrationSpeed.value;
                        line18State.motorVibrationSpeed = fTLine18ParamInfo.motorVibrationSpeed.value;
                        line18State.stepVibrationSpeed = fTLine18ParamInfo.stepVibrationSpeed.value;
                    }
                    message.data = line18State;

                }

            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 保存状态
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("SaveSimulationState")]
        public ResponseMessage SaveSimulationState(Line18State line18State)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                sHGDLine.Line18State = line18State;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 查询模拟状态
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QuerySimulationState")]
        public ResponseMessage QuerySimulationState()
        {
            ResponseMessage message = new ResponseMessage();
            SimulationInfo simulationInfo = new SimulationInfo();
            try
            {
                simulationInfo.Mode = sHGDLine.Simulation;
                simulationInfo.VirtualInterval = sHGDLine.Interval / 1000;
                message.data = simulationInfo;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }

        /// <summary>
        /// 保存模拟状态
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("SaveSimulationMode")]
        public ResponseMessage SaveSimulationMode(SimulationInfo simulationInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {

                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["Simulation"] = simulationInfo.Mode;
                    jsonObject["Interval"] = simulationInfo.VirtualInterval;
                    sHGDLine.Simulation = simulationInfo.Mode;
                    sHGDLine.Interval = simulationInfo.VirtualInterval * 1000;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新异常";
            }

            return message;
        }

        public byte[] Crc18(byte[] buffer, int start = 0, int len = 0)
        {
            if (buffer == null || buffer.Length == 0) return null;
            if (start < 0) return null;
            if (len == 0) len = buffer.Length - start;
            int length = start + len;
            if (length > buffer.Length) return null;
            ushort crc = 0xFFFF;// Initial value
            for (int i = start; i < length; i++)
            {
                crc ^= buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 1) > 0)
                        crc = (ushort)((crc >> 1) ^ 0xA001);// 0xA001 = reverse 0x8005
                    else
                        crc = (ushort)(crc >> 1);
                }
            }
            byte[] ret = BitConverter.GetBytes(crc);
            Array.Reverse(ret);
            return ret;
        }

        public byte[] CrcXmodem(byte[] data)
        {
            ushort crc = 0;
            for (int i = 0; i < data.Length; i++)
            {
                crc = (ushort)(crc ^ (ushort)(data[i] << 8));
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x8000) != 0)
                    {
                        crc = (ushort)((crc << 1) ^ 0x1021);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                }
            }
            byte[] result = new byte[2];
            result[0] = (byte)((crc & 0xFF00) >> 8);
            result[1] = (byte)(crc & 0x00FF);
            return result;
        }

        public string ToHexs(byte[] data)
        {
            if (data.Length <= 0) return "";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2") + " ");
            }
            string str = sb.ToString();
            return str;
        }

        public byte[] stringToHexByte(string hexString)
        {
            byte[] byteArray = Encoding.ASCII.GetBytes(hexString);
            return byteArray;
        }

        public int ToTwosComplement(int number, int bitCount)
        {
            int mask = (int)((1 << bitCount) - 2);
            return (int)number & mask;
        }
    }
}
